//
//  HYBPhotoPickerManager.m
//  imgtest
//
//  Created by 儒道释 on 16/2/1.
//  Copyright © 2016年 tiantianchedai. All rights reserved.
//

#import "HYBPhotoPickerManager.h"
#import <AVFoundation/AVFoundation.h>
@interface HYBPhotoPickerManager () <UIImagePickerControllerDelegate,
UINavigationControllerDelegate,
UIActionSheetDelegate>

@property (nonatomic, weak)     UIViewController          *fromController;
@property (nonatomic, copy)     HYBPickerCompelitionBlock completion;
@property (nonatomic, copy)     HYBPickerCancelBlock      cancelBlock;
@property (nonatomic,assign)    UIImagePickerControllerSourceType sourceType;
@end

@implementation HYBPhotoPickerManager

+ (HYBPhotoPickerManager *)shared {
    static HYBPhotoPickerManager *sharedObject = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        if (!sharedObject) {
            sharedObject = [[[self class] alloc] init];
        }
    });
    
    return sharedObject;
}

- (void)showActionSheetInView:(UIView *)inView
               fromController:(UIViewController *)fromController
                   completion:(HYBPickerCompelitionBlock)completion
                  cancelBlock:(HYBPickerCancelBlock)cancelBlock {
    self.completion = [completion copy];
    self.cancelBlock = [cancelBlock copy];
    self.fromController = fromController;
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UIAlertController *actionSheet = nil;
        if ([self isCameraDeviceAvailable]) {
            actionSheet  = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self chosePic];
            }];
            
            UIAlertAction *actionTwo = [UIAlertAction actionWithTitle:@"拍照上传" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                if (![self isCameraDeviceAvailable]) {
                    return;
                }
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                picker.delegate = self;
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                _sourceType = picker.sourceType;
                picker.allowsEditing = self.allowEditing;
                if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 7.0) {
                    picker.navigationBar.barTintColor = self.fromController.navigationController.navigationBar.barTintColor;
                }
                // 设置导航默认标题的颜色及字体大小
                //                picker.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor],
                //                                                             NSFontAttributeName : [UIFont boldSystemFontOfSize:18]};
                [self.fromController presentViewController:picker animated:YES completion:nil];
                self.allowEditing = NO;
                return;
            }];
            
            UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            
            [actionSheet addAction:actionOne];
            [actionSheet addAction:actionTwo];
            [actionSheet addAction:actionCancel];
        }
        else {
            actionSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self chosePic];
            }];
            UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [actionSheet addAction:actionOne];
            [actionSheet addAction:actionCancel];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [fromController presentViewController:actionSheet animated:YES completion:nil];
        });
    });
    return;
}

- (void)chosePic
{
    if ([self isPhotoLibraryAvailable]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        _sourceType = picker.sourceType;
        picker.allowsEditing = self.allowEditing;
        picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
        
        if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 7.0) {
            picker.navigationBar.barTintColor = self.fromController.navigationController.navigationBar.barTintColor;
        }
        // 设置导航默认标题的颜色及字体大小
        //        picker.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor],
        //                                                     NSFontAttributeName : [UIFont boldSystemFontOfSize:18]};
        [self.fromController presentViewController:picker animated:YES completion:nil];
    }
    self.allowEditing = NO;
    return;
}


#pragma mark - UIImagePickerControllerDelegate
// 选择了图片或者拍照了
- (void)imagePickerController:(UIImagePickerController *)aPicker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [aPicker dismissViewControllerAnimated:YES completion:nil];
    __block UIImage *image = [info valueForKey:UIImagePickerControllerEditedImage];
    
    if (image && self.completion) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
        [self.fromController setNeedsStatusBarAppearanceUpdate];
        
        //对图片进行操作
        self.completion(image);
    }
    return;
}

// 取消
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)aPicker {
    [aPicker dismissViewControllerAnimated:YES completion:nil];
    
    if (self.cancelBlock) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
        [self.fromController setNeedsStatusBarAppearanceUpdate];
        
        self.cancelBlock();
    }
    return;
}
#pragma mark - navigation代理
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status != AVAuthorizationStatusDenied) {
        return;
    }
    if(_sourceType == UIImagePickerControllerSourceTypeCamera && ![self canTakePhoto]){
        //不允许照相则提示用户
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"未获得摄像头权限,请在设备的\"设置-隐私-相机\"中允许访问相机" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles: nil];
        [alert show];
    }
    if (_sourceType == UIImagePickerControllerSourceTypePhotoLibrary && ![self isPhotoLibraryAvailable]){
        //不允许访问照片则提示用户
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"未获得照片库权限,请在设备的\"设置-隐私-照片\"中允许访问照片" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles: nil];
        [alert show];
        
    }
    
}

/**是否能拍照*/
-(BOOL)isCameraDeviceAvailable
{
    return  [UIImagePickerController isCameraDeviceAvailable: UIImagePickerControllerCameraDeviceRear];
}

/**看是否允许访问照片*/
-(BOOL)isPhotoLibraryAvailable
{
    return[UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary];
}
/**允许摄像*/
-(BOOL)canTakePhoto
{
    NSString *mediaType = AVMediaTypeVideo;// Or AVMediaTypeAudio
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    // This status is normally not visible—the AVCaptureDevice class methods for discovering devices do not return devices the user is restricted from accessing.
    BOOL isAvaluable = NO;
    if(authStatus == AVAuthorizationStatusAuthorized){
        isAvaluable = YES;
    }
    return isAvaluable;
}


+(UIImage *) imageCompressForWidth:(UIImage *)sourceImage
{
    //等比改变大小
    float multiply;
    int width = 1280;
    if (sourceImage.size.height > sourceImage.size.width) {
        multiply = width / sourceImage.size.height;
    } else multiply = width /sourceImage.size.width;
    CGFloat targetWidth = sourceImage.size.width * multiply;
    CGFloat targetHeight = sourceImage.size.height *multiply;
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0,0,targetWidth, targetHeight)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
+(NSData *)imgdataForUpload:(UIImage *)aImage
{
    UIImage *fixedImg = [HYBPhotoPickerManager fixImg:aImage];
    return UIImageJPEGRepresentation(fixedImg, 0.8);
    
}
+(UIImage *)fixImg:(UIImage *)aImage
{
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}
@end
